import {Controller, Get, Inject} from '@midwayjs/core';
import * as dgram from 'dgram';
import {Context} from "@midwayjs/koa";

@Controller('/')
export class HomeController {

  @Inject()
  ctx: Context;

  @Get('/')
  async home(): Promise<string> {
    return 'Hello Midwayjs!';
  }

  @Get('/server/udp10002Status')
  async udp10002Status(): Promise<string> {
    const serverIp: any = this.ctx.query.serverIp;
    console.info('serverIp:', serverIp);
    const serverPort: any = this.ctx.query.serverPort;
    const regexIp: RegExp = new RegExp("^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
      "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
      "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." +
      "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$");
    if (!regexIp.test(serverIp)) {
      return 'Invalid server IP address';
    }
    const regexNum: RegExp = new RegExp("^[1-9][0-9]*$");
    if (!regexNum.test(serverPort)) {
      return 'Invalid server port';
    }
    const hexMessage: any = '7463705f31303030315f69735f6f6e';
    return await this.sendUDPMessage(hexMessage, serverIp, Number(serverPort));
  }

  private sendUDPMessage(message: string, host: string, port: number): Promise<string> {
    return new Promise((resolve, reject) => {
      const client = dgram.createSocket('udp4');

      // 设置超时时间，例如5秒
      const timeout = setTimeout(() => {
        client.close();
        resolve('No response');
      }, 5000);

      // 监听进来的message事件
      client.on('message', (msg, rinfo) => {
        console.log(`Server responded with: ${msg}`);
        // 必要时取消超时
        clearTimeout(timeout);
        resolve(msg.toString());
        client.close();
      });

      // 发送消息
      client.send(Buffer.from(message, 'hex'), port, host, (err) => {
        if (err) {
          client.close();
          clearTimeout(timeout);
          reject('Failed to send message');
        }
      });
    });
  }
}
